//
// Created by denglibin on 2021/5/28.
//

#include <window.h>
#include "global.h"
#define WIN_W 800
#define WIN_H 600


/**
 * 绘制函数
 * @param window
 */
static void draw(Window* window, SDL_Event*  event);
/**
 * 事件处理函数
 * @param window
 * @param event
 */
static void handleEvent(Window* window, SDL_Event*  event);

static void changePosition();

int main_demo4(int argc, char** argv){
    GlobalInit();
    Window * window = createWindow(WIN_W, WIN_H, "demo4");
    eventLoop(window, draw, handleEvent);
    WindowFree(window);
}
 void draw(Window* window, SDL_Event* event){

     changePosition();
     //设置渲染器颜色
     SDL_SetRenderDrawColor(window->winRender, 0, 0, 0, 0);
     SDL_RenderClear(window->winRender); //用设置的颜色清除
     SDL_SetRenderDrawBlendMode(window->winRender, SDL_BLENDMODE_BLEND);//设置混合模式，支持alpha透明
     //int l = ((int )window->interval * speed / 10 );
     SDL_Rect r = {spirit->x   , spirit->y, spirit->rect_w, spirit->rect_h};
     //把渲染器设置成红色
     SDL_SetRenderDrawColor(window->winRender, 0, 255, 0, 255);
     //用矩形填充
     SDL_RenderFillRect(window->winRender, &r);

     //生效
     SDL_RenderPresent(window->winRender);
     SDL_ShowWindow(window->win);
}

void changePosition(){
    spirit->x += spirit->x_speed * spirit->x_direction;
    spirit->y += spirit->y_speed * spirit->y_direction;
}

void handleEvent(Window* window, SDL_Event*  event){
    if(event->type == SDL_KEYDOWN){
        switch (event->key.keysym.sym) {
            case SDLK_a:
               spirit->x_direction = -1;
                break;
            case SDLK_d:
                spirit->x_direction = 1;
                break;
            case SDLK_w:
                spirit->y_direction = -1;
                break;
            case SDLK_s:
                spirit->y_direction = 1;
                break;
        }
    }
    if(event->type == SDL_KEYUP){
        spirit->x_direction = 0;
        spirit->y_direction = 0;
    }
}
